package
{
	import away3d.cameras.*;
	import away3d.containers.*;
	import away3d.events.MouseEvent3D;
	import away3d.lights.DirectionalLight3D;
	import away3d.materials.*;
	import away3d.primitives.*;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import jiglib.math.JNumber3D;
	import jiglib.physics.RigidBody;
	import jiglib.plugin.away3d.Away3DPhysics;
	import jiglib.plugin.away3d.Away3dMesh;
		
	[SWF(width="640",height="400",frameRate=30)]
	public class Jiglib extends Sprite
	{
		
		[Embed(source="images/diceTexture1.png")]
		private static var diceTexture1:Class;
		
		[Embed(source="images/diceTexture2.png")]
		private static var diceTexture2:Class;

		[Embed(source="images/diceTexture3.png")]
		private static var diceTexture3:Class;

		[Embed(source="images/diceTexture4.png")]
		private static var diceTexture4:Class;
		
		[Embed(source="images/diceTexture5.png")]
		private static var diceTexture5:Class;
		
		[Embed(source="images/diceTexture6.png")]
		private static var diceTexture6:Class;
		
		[Embed(source="images/walltexture.png")]
		private static var walltexture:Class;
		
		[Embed(source="images/groundtexture.png")]
		private static var groundtexture:Class;
			
		private var scene:Scene3D;
		private var camera:HoverCamera3D;
		private var view:View3D;
		private var light:DirectionalLight3D;
		private var physics:Away3DPhysics;
		
		
		private var boxWidth:Number = 250
		private var boxHeight:Number = 30
		private var boxDepth:Number = 250
		private var boxThickness:Number = 5
		
		private var diceTextures:Array = [ new WhiteShadingBitmapMaterial(( new diceTexture1() as Bitmap).bitmapData ),
			new WhiteShadingBitmapMaterial( (new diceTexture2() as Bitmap).bitmapData ),
			new WhiteShadingBitmapMaterial( (new diceTexture3() as Bitmap).bitmapData ),
			new WhiteShadingBitmapMaterial( (new diceTexture4() as Bitmap).bitmapData ),
			new WhiteShadingBitmapMaterial( (new diceTexture5() as Bitmap).bitmapData ),
			new WhiteShadingBitmapMaterial( (new diceTexture6() as Bitmap).bitmapData ) ];
		
		
		
		private var wallTexture:WhiteShadingBitmapMaterial = new WhiteShadingBitmapMaterial( (new walltexture() as Bitmap).bitmapData)
		private var groundTexture:WhiteShadingBitmapMaterial = new WhiteShadingBitmapMaterial( (new groundtexture() as Bitmap).bitmapData)
		
		private var diceScale:Number = 30;
		private var dices:Array = new Array();
		private var diceRandomForce:Number = 50;
		
		private var ground:RigidBody;
		
		private function initAway3D():void {
			scene = new Scene3D({x:0, y:0});
			
			camera = new HoverCamera3D();
			camera.distance = 950;
			
			light = new DirectionalLight3D({color:0xFFFFFF, ambient:0.25, diffuse:0.75, specular:0.9})
			scene.addChild(light)
			
			view=new View3D({scene:scene,camera:camera});
			view.x=0;
			view.y=stage.stageHeight;
			addChild(view);

			physics = new Away3DPhysics(view,9.8)
	
			
		}
		
		private function createWalls():void {
			
			/*var left:RigidBody = physics.createCube({width:boxThickness, height:boxHeight, depth:boxDepth});
			left.movable = false;
			left.x = -(boxWidth+boxThickness) + stage.stageWidth; 
			//left.x  stage.stageWidth/2; 
			Away3dMesh(left.skin).mesh.material = wallTexture
			
			var right:RigidBody = physics.createCube({width:boxThickness, height:boxHeight, depth:boxDepth});
			right.movable = false;
			right.x =  stage.stageWidth; //(boxWidth+boxThickness)/2
			Away3dMesh(right.skin).mesh.material = wallTexture
			
			var front:RigidBody = physics.createCube({width:boxWidth, height:boxHeight, depth:boxThickness});
			front.movable = false;
			front.z =  (boxDepth+boxThickness)/2
			Away3dMesh(front.skin).mesh.material = wallTexture
			
			var back:RigidBody = physics.createCube({width:boxWidth, height:boxHeight, depth:boxThickness});
			back.movable = false;
			back.z = -(boxDepth+boxThickness)/2
			Away3dMesh(back.skin).mesh.material = wallTexture
			*/
			ground = physics.createCube({width:boxWidth*2, height:boxThickness, depth:boxDepth*2, segmentsW:2, segmentsH:2});
			
			ground.movable = false;
			ground.y = 10;//-(boxHeight+boxThickness)/2
			ground.x = stage.stageWidth - boxWidth - boxThickness;
			
			Away3dMesh(ground.skin).mesh.material = groundTexture;
			Away3dMesh(ground.skin).mesh.pushback = true;
			
		}
		
		private function createDice():void {
			var dice:RigidBody = physics.createCube({width:diceScale, height:diceScale, depth:diceScale});
			
			//dice.y=500;
			dice.mass = 0.2;
			dice.movable=true
			
			
			Away3dMesh(dice.skin).mesh.extra = dice;
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.left = diceTextures[0]
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.right = diceTextures[1]
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.front = diceTextures[2]
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.back = diceTextures[3]
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.top = diceTextures[4]
			Cube(Away3dMesh(dice.skin).mesh).cubeMaterials.bottom = diceTextures[5]
				
			Away3dMesh(dice.skin).mesh.addOnMouseOver(setInactive);
			
			dices.push(dice);
			dice.moveTo( new JNumber3D( 0, 40 , 0 ) );
			addRandomForce(dice);
			
			for(var i:int = 0; i < dices.length; i ++){
				for(var j:int = 0; j < dices.length; j ++){
					(dices[i] as RigidBody).disableCollisions(dices[j]);
				}
			}
		}
		
		private function setInactive(e:MouseEvent3D):void{
			trace("Aca");
			(e.object.extra as RigidBody).setInactive();
		}
		
		private function resetAllDices(e:Event):void {

			
				
			for(var i:int = 0; i < dices.length; i ++){
				for(var j:int = 0; j < dices.length; j ++){
					(dices[i] as RigidBody).disableCollisions(dices[j]);
				}
			}
			
			for(i = 0; i<dices.length; i++) {
				dices[i].moveTo( new JNumber3D( 0, 100 , 0 ) )
				addRandomForce(dices[i])
			}
		}
		private function resetOnlyPositions():void {
			for(var i:int = 0; i<dices.length; i++) {
				dices[i].moveTo( new JNumber3D( 0, 10 , 0 ) )
			}
		}
		
		private function addRandomForce(rigid:RigidBody):void {
			
			var forceX:Number =  Math.random()*10+ 40;
			var forceY:Number =  Math.random()* 10 + 65;
			var forceZ:Number =  0;
			rigid.setVelocity(new JNumber3D(forceX,forceY,forceZ));
			rigid.setAngVel(new JNumber3D(Math.random(),Math.random(),Math.random()));
			//rigid.applyBodyWorldImpulse(new JNumber3D(forceX,forceY,forceZ), new JNumber3D(rigid.currentState.position.x + diceScale/2,rigid.currentState.position.y+ diceScale/2,rigid.currentState.position.z+ diceScale/2));
			//rigid.addBodyForce(new JNumber3D(-forceX,-forceY,-forceZ) , new JNumber3D(rigid.x - diceScale,rigid.y,rigid.z) )
			
		}
		
		private function initListeners():void {
			stage.addEventListener(Event.ENTER_FRAME, render);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,resetAllDices)
		}
		
		private function render( e:Event ):void {
			var array:Array = new Array();
			
			for(var i:int = 0; i < dices.length; i ++){
				
				if((dices[i] as RigidBody).x > stage.stageWidth ||  (dices[i] as RigidBody).y < -stage.stageWidth*0/2){
					physics.removeBody(dices[i]);
					view.scene.removeChild(Cube(Away3dMesh(dices[i].skin).mesh));
					dices.splice(i,1);
				}
					
					//(dices[i] as RigidBody).setInactive();
			}
			
			view.render();
			
			camera.targetpanangle = stage.mouseX/stage.stageWidth*360
			camera.targettiltangle = stage.mouseY/stage.stageHeight*30
			camera.hover();
			physics.step();
			
			light.x = camera.x
			light.y = camera.y
			light.z = camera.z
		}
		
		
		
		public function Jiglib()
		{
			initAway3D();
			createWalls();
			var timer:Timer = new Timer(200);
			timer.addEventListener(TimerEvent.TIMER, createCube);
			timer.start();
			
			//resetOnlyPositions()
			initListeners();	
		}
		
		private function createCube(e:TimerEvent):void{
			createDice();
		}
	}
}